/*
 * Copyright (c) 2017, www.zm0618.com All Rights Reserved..
 */

package com.light.hessian.remoting.client.balance;

import com.light.hessian.provider.config.ProviderStatus;
import com.light.hessian.provider.slot.ProviderStatusSlot;
import com.light.hessian.provider.slot.SlotRuntime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by zhaojun on 2017/02/16.
 */
public class LRTBalancer extends BaseBalancer{

    protected static  final Logger logger= LoggerFactory.getLogger(LRTBalancer.class);
    public LRTBalancer() {

    }


    public LRTBalancer(List<ProviderStatusSlot> statusSlots) {
        super(statusSlots);
    }

    //最短响应时间
    @Override
    public String getBalancerName() {
        return Balance.lrt.name();
    }

    @Override
    public ProviderStatusSlot select() {
        long min=Long.MAX_VALUE;
        ProviderStatusSlot statusSlot=null;
        ProviderStatusSlot[] cStatusSlots = statusSlots;
        int index =-1;
        for (int i = 0; i <cStatusSlots.length ; i++) {
            statusSlot = cStatusSlots[i];
            if (statusSlot.getStatus()== ProviderStatus.UP){
                SlotRuntime runtime = statusSlot.getRuntime();
                long enterTime = runtime.getEnterTime();
                long outTime = runtime.getOutTime();
                long deltaTime=outTime-enterTime;
                if (deltaTime<=min){
                     min=deltaTime;
                     index = i;
                }
            }
        }

        if (index>=0){
            if (cStatusSlots[index].isShowBalancer()){
                logger.info("=====>{}",cStatusSlots[index]);
            }
            return cStatusSlots[index];
        }else{
            return failback(index,cStatusSlots);
        }
    }


}
